package com.vdimitr.happycube.puzzle.solution.output.writer;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * This class holds the template method used for printing the translated puzzle
 * piece solution into a string array. Derived classes need to set the
 * OutputStream to be used.
 * 
 * 
 * @author vasileios.dimitriadis
 * 
 */
public abstract class AbstractPuzzlePieceSolutionWriter implements
		IPuzzlePieceSolutionOutputWriter {

	@Override
	public void writeSolution(String[] stingArray) throws IOException {
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new OutputStreamWriter(
					getOutputStream()));
			for (String string : stingArray) {
				writer.write(string);
				writer.newLine();
			}
			writer.flush();
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}

	/**
	 * Derived classes should implement this method to set the OutputStream used
	 * during the writing of the solution
	 * 
	 * @return the OutputStream to use during writing the solution
	 * @throws IOException
	 *             for those cases where the instantiation of the OutputStream
	 *             throws exception
	 */
	protected abstract OutputStream getOutputStream() throws IOException;

}
